package web.interceptor;

import common.RequireLogin;
import common.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequireLoginInterceptor extends HandlerInterceptorAdapter
{
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if(handler instanceof HandlerMethod)
        {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequireLogin  requireLogin  = handlerMethod.
                          getMethodAnnotation(RequireLogin.class);
            if(requireLogin!=null && UserContext.getCurrentUser()==null)
            {
                response.sendRedirect("/login.html");
                return false;
            }
        }
        return super.preHandle(request, response, handler)       ;
    }
}
